﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace OrderManager.Orders.Http
{
    class HttpUtil
    {
        public static Regex REG_URL_ENCODING = new Regex(@"%[a-f0-9]{2}");

        public static string DoPost(string serviceURL, Dictionary<string, string> parameter)
        {
            HttpWebRequest req = (HttpWebRequest)(WebRequest.Create(serviceURL));

            req.ServicePoint.Expect100Continue = false;
            req.Method = "POST";
            req.KeepAlive = true;
            req.UserAgent = "sszg";
            req.Timeout = 5000;
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            string requestPram = string.Join("&", parameter.Select(item => item.Key + "=" + UrlEncode(item.Value, Encoding.GetEncoding("utf-8"))));

            byte[] postData = Encoding.UTF8.GetBytes(requestPram);
            var stream = req.GetRequestStream();
            stream.Write(postData, 0, postData.Length);
            stream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);

            StreamReader reader = null;
            try
            {
                reader = new StreamReader(rsp.GetResponseStream(), Encoding.GetEncoding(rsp.CharacterSet));
                string content = reader.ReadToEnd();
                return content;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }

        /**
* C#的URL encoding有两个问题：
* 1.左右括号没有转移（Java的URLEncoder.encode有）
* 2.转移符合都是小写的，Java是大写的
*/
        public static string UrlEncode(string str, Encoding e)
        {
            if (str == null)
            {
                return null;
            }

            String stringToEncode = HttpUtility.UrlEncode(str, e).Replace("+", "%20").Replace("*", "%2A").Replace("(", "%28").Replace(")", "%29");
            return REG_URL_ENCODING.Replace(stringToEncode, m => m.Value.ToUpperInvariant());
        }
    }
}
